import React, { useState } from 'react';
import authApi from '../../api/auth';

const TestApiPage: React.FC = () => {
  const [result, setResult] = useState<any>(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string>('');

  // 测试登录
  const testLogin = async () => {
    setLoading(true);
    setError('');
    setResult(null);
    
    try {
      const response = await authApi.login({
        username: 'admin',
        password: '123456',
        isQuick: true
      });
      
      setResult({
        type: '登录成功',
        data: response
      });
      
      // 保存token到localStorage
      if (response.data && response.data.accessToken) {
        localStorage.setItem('token', response.data.accessToken);
        console.log('Token已保存:', response.data.accessToken);
      }
    } catch (err: any) {
      setError(`登录失败: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 测试获取用户信息
  const testGetUser = async () => {
    setLoading(true);
    setError('');
    setResult(null);
    
    const token = localStorage.getItem('token');
    if (!token) {
      setError('没有token，请先登录');
      setLoading(false);
      return;
    }
    
    try {
      const response = await authApi.getUser();
      setResult({
        type: '获取用户信息成功',
        data: response
      });
    } catch (err: any) {
      setError(`获取用户信息失败: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 直接用fetch测试
  const testWithFetch = async () => {
    setLoading(true);
    setError('');
    setResult(null);
    
    const token = localStorage.getItem('token');
    if (!token) {
      setError('没有token，请先登录');
      setLoading(false);
      return;
    }
    
    try {
      const response = await fetch('http://localhost:8086/user/detail', {
        method: 'GET',
        headers: {
          'Authorization': `Bearer ${token}`,
          'Content-Type': 'application/json',
        },
        credentials: 'include'
      });
      
      const data = await response.json();
      
      if (response.ok) {
        setResult({
          type: 'Fetch请求成功',
          data: data
        });
      } else {
        setError(`Fetch请求失败: ${response.status} ${response.statusText} - ${data.message || ''}`);
      }
    } catch (err: any) {
      setError(`Fetch请求异常: ${err.message}`);
    } finally {
      setLoading(false);
    }
  };

  // 清除token
  const clearToken = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('userInfo');
    setResult(null);
    setError('');
    console.log('Token已清除');
  };

  return (
    <div className="min-h-screen bg-gray-50 p-8">
      <div className="max-w-4xl mx-auto">
        <h1 className="text-3xl font-bold text-gray-900 mb-8">API测试页面</h1>
        
        {/* 按钮组 */}
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4 mb-8">
          <button
            onClick={testLogin}
            disabled={loading}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
          >
            {loading ? '请求中...' : '1. 测试登录'}
          </button>
          
          <button
            onClick={testGetUser}
            disabled={loading}
            className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50"
          >
            {loading ? '请求中...' : '2. 获取用户信息'}
          </button>
          
          <button
            onClick={testWithFetch}
            disabled={loading}
            className="px-4 py-2 bg-purple-600 text-white rounded-lg hover:bg-purple-700 disabled:opacity-50"
          >
            {loading ? '请求中...' : '3. Fetch直接请求'}
          </button>
          
          <button
            onClick={clearToken}
            className="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700"
          >
            清除Token
          </button>
        </div>

        {/* Token显示 */}
        <div className="bg-white rounded-lg shadow p-6 mb-6">
          <h2 className="text-xl font-semibold mb-4">当前Token状态</h2>
          <div className="bg-gray-100 p-4 rounded">
            <p className="text-sm text-gray-600">Token:</p>
            <p className="font-mono text-sm break-all">
              {localStorage.getItem('token') || '无Token'}
            </p>
          </div>
        </div>

        {/* 错误显示 */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <h2 className="text-lg font-semibold text-red-800 mb-2">错误信息</h2>
            <p className="text-red-700">{error}</p>
          </div>
        )}

        {/* 结果显示 */}
        {result && (
          <div className="bg-white rounded-lg shadow p-6">
            <h2 className="text-xl font-semibold mb-4">{result.type}</h2>
            <div className="bg-gray-100 p-4 rounded">
              <pre className="text-sm overflow-auto">
                {JSON.stringify(result.data, null, 2)}
              </pre>
            </div>
          </div>
        )}

        {/* 使用说明 */}
        <div className="bg-blue-50 border border-blue-200 rounded-lg p-6 mt-8">
          <h2 className="text-lg font-semibold text-blue-800 mb-4">使用说明</h2>
          <ol className="list-decimal list-inside space-y-2 text-blue-700">
            <li>先点击"测试登录"获取token</li>
            <li>然后点击"获取用户信息"或"Fetch直接请求"测试API</li>
            <li>查看返回的数据和错误信息</li>
            <li>如需重新测试，可以点击"清除Token"</li>
          </ol>
        </div>
      </div>
    </div>
  );
};

export default TestApiPage;